package com.u21.a0903_onlinemusic.words;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.u21.a0903_onlinemusic.R;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WordActivity extends Activity {

	private MediaPlayer mediaPlayer;
	private TextView wordMain, wordExp;
	private List<String> list = new ArrayList<String>();
	private RelativeLayout relativeLayout;


	String word;
	String name;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		Intent intent = getIntent();
		word = intent.getStringExtra("Word");

		setContentView(R.layout.activity_randwords);
		relativeLayout = findViewById(R.id.randwordsInterface);
		wordMain = findViewById(R.id.wordmain);
		wordExp = findViewById(R.id.wordexp);


		int index = word.indexOf("|");


		name = word.substring(0, index);
		String explain = word.substring(index + 1);
		StringBuilder stringBuilder = new StringBuilder(explain);

		String[] sign = {"a.", "v.", "n.", "vi.", "vt.", "ad.", "adj.", "adv.", "pron."};
		for (String s : sign) {
			if (explain.indexOf(s) > 0) {
				stringBuilder.insert(explain.indexOf(s), "\n");
			}
		}

		wordMain.setText(name);
		wordExp.setText(stringBuilder);
		wordMain.setOnClickListener(v -> {
			playPron(name);
			mediaPlayer = null;
		});
		wordExp.setOnClickListener(v -> {
			playPron(explain);
			mediaPlayer = null;
		});
		relativeLayout.setOnClickListener(v -> {
			Runtime runtime = Runtime.getRuntime();
			try {
				runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);
			} catch (IOException e) {
				e.printStackTrace();
			}
		});


	}

	private void playPron(String text) {
		//如果多媒体对象不为空，实例化多媒体对象
		if (mediaPlayer == null) {
			mediaPlayer = new MediaPlayer();

		}
		//为了实现多媒体同一时间只播放一首音乐，我们必须对多媒体对象做同步处理
		synchronized (mediaPlayer) {
			//实现多媒体对音乐的播放
			try {
				//设置播放音乐源—播放音乐的网络链接
				mediaPlayer.setDataSource("https://dict.youdao.com/dictvoice?audio=" + text);
				//播放器做播放准备
				mediaPlayer.prepare();
				//获取到音乐播放总时间

				mediaPlayer.start();

			} catch (Exception e) {
				e.printStackTrace();
			}


		}

	}


}
